<template>
  <div class="volunteer-profile">
    <el-card class="profile-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>个人资料</h3>
          <el-button type="primary" @click="handleSubmit" :loading="loading">保存修改</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="profile-form">
        <!-- 头像上传 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :auto-upload="false"
            :http-request="customUpload">
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 基本信息 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>

        <el-form-item label="所在地区" prop="location">
          <el-cascader
            v-model="form.location"
            :options="locationOptions"
            placeholder="请选择所在地区"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 志愿者信息 -->
        <div class="section-divider">志愿者信息</div>

        <el-form-item label="志愿领域" prop="volunteerAreas">
          <el-select
            v-model="form.volunteerAreas"
            multiple
            placeholder="请选择志愿领域"
            style="width: 100%">
            <el-option
              v-for="item in volunteerAreaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="技能特长" prop="skills">
          <el-select
            v-model="form.skills"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入技能特长"
            style="width: 100%">
            <el-option
              v-for="item in skillOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input
            v-model="form.bio"
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getVolunteerProfile, updateVolunteerProfile, uploadAvatar } from '@/api/volunteer-dashboard'

const formRef = ref(null)
const form = ref({
  avatar: '',
  username: '',
  realName: '',
  gender: '',
  birthday: '',
  phone: '',
  email: '',
  location: [],
  volunteerAreas: [],
  skills: [],
  bio: ''
})

const loading = ref(false)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 模拟数据
const locationOptions = [
  {
    value: 'guangdong',
    label: '广东省',
    children: [
      {
        value: 'shenzhen',
        label: '深圳市',
        children: [
          { value: 'nanshan', label: '南山区' },
          { value: 'futian', label: '福田区' }
        ]
      }
    ]
  }
]

const volunteerAreaOptions = [
  { value: 'ocean', label: '海洋保护' },
  { value: 'education', label: '环保教育' },
  { value: 'rescue', label: '生物救助' }
]

const skillOptions = [
  { value: 'diving', label: '潜水' },
  { value: 'photography', label: '摄影' },
  { value: 'teaching', label: '教学' }
]

// 获取个人资料
const fetchProfile = async () => {
  loading.value = true
  try {
    const res = await getVolunteerProfile()
    // 设置表单数据
    Object.keys(form.value).forEach(key => {
      if (res.data[key] !== undefined) {
        form.value[key] = res.data[key]
      }
    })
  } catch (error) {
    console.error('获取个人资料失败', error)
    ElMessage.error('获取个人资料失败')
  } finally {
    loading.value = false
  }
}

// 头像上传
const handleAvatarSuccess = async (res) => {
  form.value.avatar = res.data.url
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 自定义上传
const customUpload = async (file) => {
  if (!beforeAvatarUpload(file)) {
    return
  }
  
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadAvatar(formData)
    form.value.avatar = res.data.url
    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败', error)
    ElMessage.error('上传失败')
  } finally {
    loadingInstance.close()
  }
  
  return false // 阻止默认上传
}

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    await updateVolunteerProfile(form.value)
    
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchProfile()
})
</script>

<style scoped lang="scss">
.volunteer-profile {
  .profile-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }

  .profile-form {
    max-width: 600px;
    margin: 0 auto;
  }

  .section-divider {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 24px 0 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409EFF;
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
    object-fit: cover;
  }
}
</style> 